package com.atguigu.day07;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;

public class Flink04_ProcessingTime_Timer_Exec {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //2.从端口读取数据
        KeyedStream<WaterSensor, Tuple> keyedStream = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                })
                .keyBy("id");

        //TODO 3.监控水位传感器的水位值，如果水位值在五秒钟之内连续上升，则报警，并将报警信息输出到侧输出流。
        SingleOutputStreamOperator<String> result = keyedStream.process(new KeyedProcessFunction<Tuple, WaterSensor, String>() {
            //上一次水位
            private Integer lastVc = Integer.MIN_VALUE;
            //定时器时间
            private Long lastTimer = Long.MIN_VALUE;

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                //1.判断水位是否上升
                if (value.getVc() > lastVc) {
                    //如果定时器没有被注册则注册一个定时器
                    if (lastTimer == Long.MIN_VALUE) {
                        //注册一个定时器
                        long timer = ctx.timerService().currentProcessingTime() + 5000;
                        System.out.println("注册定时器："+ctx.getCurrentKey()+":"+timer);
                        //更新定时器的时间
                        lastTimer = timer;
                        ctx.timerService().registerProcessingTimeTimer(timer);
                    }
                } else {
                    //水位没有上升
                    //判断是否已经有注册的定时器，有的话则删除定时器不让其报警，没有的话什么不干
                    if (lastTimer != Long.MIN_VALUE) {
                        System.out.println("删除定时器："+ctx.getCurrentKey()+":"+lastTimer);
                        //删除定时器
                        ctx.timerService().deleteProcessingTimeTimer(lastTimer);
                        //重置定时器时间
                        lastTimer = Long.MIN_VALUE;
                    }
                }
                //将当前值保存起来，给下一次水位过来之后判断是否上升
                lastVc = value.getVc();
            }

            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                System.out.println("重置定时器！！！");
                //重置定时器时间
                lastTimer = Long.MIN_VALUE;
                ctx.output(new OutputTag<String>("output") {
                }, "注意！！！！！水位5S内连续上升");
            }
        });

        result.getSideOutput(new OutputTag<String>("output") {
        }).print();

        env.execute();
    }
}
